package com.music.task;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.music.entity.Song;
import com.music.service.TopService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.*;

@Component
public class TopListTask {
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private TopService topService;
    

    /**
     * 流行指数定时器
     * @return
     * @throws JsonProcessingException
     */
    @Scheduled(cron = "0 0 0 * * ? ")
    public Double[][] change() throws JsonProcessingException {
        Boolean existLastSong=redisTemplate.hasKey("lastSong");
        if(existLastSong){
            redisTemplate.delete("lastSong");
        }
        redisTemplate.rename("todaySong","lastSong");
        topService.catchSongToRedis();
        List lastList= redisTemplate.opsForList().range("lastSong",0,-1);
        List todayList=redisTemplate.opsForList().range("todaySong",0,-1);
        ObjectMapper objectMapper = new ObjectMapper();
        List<Song> list=new ArrayList<Song>();
        List<Song> list1=new ArrayList<Song>();
        Double Num;

        for(Object o:lastList){
            Song song = objectMapper.readValue(objectMapper.writeValueAsString(o), Song.class);
            list.add(song);
        }
        for(Object o:todayList){
            Song song = objectMapper.readValue(objectMapper.writeValueAsString(o), Song.class);
            list1.add(song);
        }
        Double a[][]=new Double[list.size()][2];
        int b=0;
        for(int i=0;i<list1.size();i++){
            for(int j=0;j<list.size();j++){
                if(list1.get(i).getSongId().equals(list.get(j).getSongId())){
                    Num=new BigDecimal((float)list1.get(i).getSongPlayCount()/list.get(j).getSongPlayCount()).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                    a[b][0]=Num;
                    a[b][1]=Double.parseDouble(list.get(j).getSongId());
                    b++;
                    break;
                }
            }
        }
        Arrays.sort(a, new Comparator<Double[]>() {
            @Override
            public int compare(Double[] o1, Double[] o2) {
                if(o2[0]-o1[0]>0){
                    return 1;
                }else if(o2[0]-o1[0]<0){
                    return -1;
                }else{
                    return 0;
                }

            }
        });


        return a;

    }
}
